import {defineStore} from 'pinia';
import {ChatMsg} from "../models/task.ts";


// 定义 state 类型
interface ChatStoreState {
    remoteIp: string;
    peerIp: string; //chat聊天时的对方IP
    messageList: ChatMsg[];
}

// 定义一个 name 为‘blogStore’的 store
export const useChatStore = defineStore('chatStore', {
    // 第三方插件的持久化配置
    persist: {
        enabled: true,
        strategies: [{
            storage: sessionStorage
        }]
    },
    state: (): ChatStoreState => {
        return {
            remoteIp: "",
            messageList: [], // 列表数据
        };
    },
    getters: {
        getMessageList(state): any[] {
            return state.messageList;
        },
    },
    actions: {
        setRemoteIP(remoteIp: string){
            return this.remoteIp = remoteIp;
        }
        ,setPeerIP(peerIp: string){
            return this.peerIp = peerIp;
        }
        /**
         * 根据Id，查询task
         * @returns {Promise<*>}
         * @param id
         */
        ,getMessageById(id: number) {
            if (!id) {
                new Error("id不能为空");
            }
            return this.messageList.find(e => {
                return e.id === id
            })
        }
        /**
         * 添加到列表
         * @return true表示添加成功，false表示已经存在了，不再添加
         */
        ,addToList(msg: ChatMsg): boolean {
            //要去重复
            if (!this.getMessageById(msg.id)) {
                this.messageList.push(msg); //添加到数组尾巴
                return true;
            } else {
                return false;
            }
        }
    }
});